<?php
App::uses('CakeEmail', 'Network/Email');
App::uses('CakeTime','Utility');
App::uses('CakeNumber', 'Utility');


class OrdersController extends AppController {
	var $components = array(
		'Cart',
		'Auth' => array(
			'allowedActions' => array('index', 'summary', 'update','emptyCart','confirm','confirmed','delete','details'),
		),
		'OrderDetails',
		'BagabEmail'
	);
	var $uses = array('Order','User','Address','Product');
	
	var $helpers = array('ProductBuilder');
	
	public function beforeRender(){
		$this->set('isrental',true);
	}
	
	///Get the current state of the cart.
	public function index()
	{
		$this->set('subtitle','Validez votre Panier');
		$this->set('paragraph_for_subtitle','S&eacute;lectionnez une date avant de valider votre panier.');
		$orderDetails = $this->OrderDetails->getOrderDetails();
		$this->set('Cart',$this->Cart->getCart());
		$this->set('bookingstartdate',isset($orderDetails['Order']['bookingstartdate'])?$orderDetails['Order']['bookingstartdate']:'');
		$this->set('bookingenddate',isset($orderDetails['Order']['bookingenddate'])?$orderDetails['Order']['bookingenddate']:'');
		
		if(!empty($this->data))
		{
			$bookingstartdate = $this->data['Order']['bookingstartdate'];
			$bookingenddate = $this->data['Order']['bookingenddate'];
			if(date($bookingstartdate)<date($bookingenddate) && $bookingstartdate>date("Y-m-d")){
				$this->OrderDetails->addOrderDetails($bookingstartdate,$bookingenddate);
				$this->redirect(array('controller'=>'orders','action'=>'details'));
			}else{
				$this->set('error_for_layout',array('Selectionnez des dates diff&eacute;rentes.'));
			}
		}
	}
	
	///Update Order during Checkout.
	public function update(){
		Configure::write('debug',0);
		$this->layout = 'ajax';
		if(!empty($this->data)){
			$request = json_decode($this->data,true);
			$orderId = $request['id'];
			$number = $request['number'];
			$response = $this->Cart->updateOrder($orderId,$number);

			echo json_encode($response);
			exit;
		}
		echo json_encode(false);
		exit;
	}
	
	///Delete Order during Checkout.
	public function delete()
	{
		Configure::write('debug',0);
		$this->layout = 'ajax';
		if(!empty($this->data)){
			$request = json_decode($this->data,true);
			$orderId = $request['id'];
			$response = $this->Cart->deleteOrder($orderId);

			echo json_encode($response);
			exit;
		}
		echo json_encode(false);
		exit;
	}
	
	public function emptyCart(){
		$this->Cart->emptyCart();
		$this->redirect(array('controller'=>'products','action'=>'index'));
	}
	
	public function details()
	{
		$this->set('subtitle','Identifiez-vous');
		$this->set('paragraph_for_subtitle','Avant de pouvoir satisfaire &agrave; votre commande, nous avons besoin d\'en savoir plus sur vous.');
		if($this->Cart->isEmpty())
		{
			$this->redirect(array('controller'=>'products','action'=>'index'));
		}
		//This is a POST
		if(!empty($this->data)){
			//Either a Log In POST
			if(isset($this->data['login'])){
				if ($this->Auth->login()) {
					$userId = $this->Auth->User('id');
					$this->User->read(null, $userId);
					$this->User->set('lastlogin',CakeTime::format('Y-m-d H:i:s',date('Y-m-d H:i:s'),false,new DateTimeZone('Europe/Paris')));
					$this->User->save();
					$this->request->data = $this->User->findAllById($userId)[0];
					$this->request->data['BillingAddress'] = $this->request->data['Address'];
					$this->request->data['User']['password']='';
				}else{
					$this->set('error_for_layout',array('Nous n\'avons pas pu vous identifier.'));
				}
			}
			//Or a Details Validation POST
			if(isset($this->data['ValidateCustomerDetails']))
			{
				$userDetails = $this->data['User'];
				$shippingAddress = $this->data['Shippingaddress'];
				if(!$this->Address->validates($shippingAddress))
				{
					$shippingAddress = null;
				}
				$billingAddress = $this->data['Billingaddress'];
				if(!$this->Address->validates($billingAddress))
				{
					$billingAddress = null;
				}
				$userTelephone = $this->data['Phonenumber'];
				$this->OrderDetails->addUserDetails($userDetails,$billingAddress,$shippingAddress,$userTelephone);
				$order = $this->formatOrder();
				$this->Order->set($order);				
				if(!$this->Order->validates() || !isset($this->data['agree']) || !$this->data['agree']){
					$errorMessage = 'Votre r&eacute;servation n\'a pas pu avoir lieu, veuillez v&eacute;rifiez vos donn&eacute;es.';
					$this->set('errors',$this->Order->invalidFields());
					$this->set('error_for_layout', array($errorMessage));
					return;
				}
				$this->redirect(array('action'=>'confirmed'));
			}
		}else{
			//This is a GET => Load the Logged in User if any
			if($this->Session->check('Auth.User')){
				$userId = $this->Session->read('Auth.User.id');
				$this->request->data = $this->User->findAllById($userId)[0];
				$this->request->data['Billingaddress'] = $this->request->data['Address'];
				$this->request->data['Billingaddress']['firstname']=$this->Session->read('Auth.User.firstname');
				$this->request->data['Billingaddress']['lastname']=$this->Session->read('Auth.User.lastname');
				$this->request->data['User']['password']='';
			}		
		}
	}
	
	public function confirm(){
		$this->set('subtitle','Confirmez votre commande');
		$this->set('paragraph_for_subtitle','V&eacute;rifiez votre commande avant de la confirmer.');
		if($this->Cart->isEmpty())
		{
			$this->redirect(array('controller'=>'products','action'=>'index'));
		}
	}
	
	///Send the order.
	public function confirmed()
	{
		$this->set('subtitle','F&eacute;licitations');
		$this->set('paragraph_for_subtitle','Votre r&eacute;servation a &eacute;t&eacute; effectu&eacute;e avec succ&egrave;s.');		
		if($this->Cart->isEmpty())
		{
			$this->redirect(array('controller'=>'products','action'=>'index'));
		}
		$order = $this->formatOrder();
		//Propagate the agreement value
		$this->Order->set($order);
		if(!$this->Order->validates()){
			//There are validation errors
			$this->Order->validationErrors;
			$this->redirect(array('action'=>'details'));
		}
		$this->Order->create();
		
		if($this->Order->saveAll($order)){
			//The order has been created
			$orderid = $this->Order->id;
			
			$order = $this->Order->findById($orderid);
			
			$orderProductList = &$order['OrdersProduct'];
			
			foreach($orderProductList as &$orderProduct){
				$product = $this->Product->findAllById(intval($orderProduct['product_id']));
				$orderProduct = array_merge($orderProduct,$product[0]);
			}
			
			$this->set('order',$order);
			$this->Cart->emptyCart();
			$this->OrderDetails->emptyAll();
			//Write the email
			$this->BagabEmail->bookingConfirmed(
					$order
				);
			$this->BagabEmail->bookingNotification(
					$order
				);
		}
	}
	
	///Summarize the order.
	public function summary(){
	
	}
	
	/**
	/Order
	/BillingAddress
	/ShippingAddress
	/
	**/
	
	private function formatOrder(){
		$cart = $this->Cart->getCart();
		$orderDetails = $this->OrderDetails->getOrderDetails();
		//Define useful data
		$products = $this->Cart->getProducts();
		$customer = $orderDetails['User'];
		$preferredPhoneNumber = $orderDetails['Phonenumber'];
		$billingAddress = (!empty($orderDetails['Billingaddress']['line1']) && !empty($orderDetails['Billingaddress']['postcode'])?
									$orderDetails['Billingaddress'] : null);
		$shippingAddress = (!empty($orderDetails['Shippingaddress']['line1']) && !empty($orderDetails['Shippingaddress']['postcode'])?
									$orderDetails['Shippingaddress'] : null);
		$bookingStartDate = $orderDetails['Order']['bookingstartdate'];
		$bookingEndDate = $orderDetails['Order']['bookingenddate'];

		$order = array();
				//Is the user logged in?
		$order['user_id'] = ($this->Session->check('Auth.User') ? $this->Session->read('Auth.User.id') : null);
		$order['title'] = isset($customer['title'])?$customer['title']:null;
		$order['firstname'] = $customer['firstname'];
		$order['lastname'] = $customer['lastname'];
		$order['associatenumber'] = $customer['associatenumber'];
		$order['email'] = $customer['email'];
		$order['phonenumber'] = $preferredPhoneNumber['phonenumber'];
		$order['total'] = (isset($cart['summary']['totalPrice']) ?  $cart['summary']['totalPrice']: 0);
		$order['bookingstartdate'] = CakeTime::format('Y-m-d H:i:s',$bookingStartDate,false,new DateTimeZone('Europe/Paris'));
		$order['bookingenddate'] = CakeTime::format('Y-m-d H:i:s',$bookingEndDate,false,new DateTimeZone('Europe/Paris'));
		$order['laststatusupdate'] = CakeTime::format('Y-m-d H:i:s',date('Y-m-d H:i:s'),false,new DateTimeZone('Europe/Paris'));
		$order['orderdate'] = CakeTime::format('Y-m-d H:i:s',date('Y-m-d H:i:s'),false,new DateTimeZone('Europe/Paris'));
		
		return array(
			'Order'=>$order,
			'Phonenumber'=>$preferredPhoneNumber,
			'OrdersProduct'=>$products,
			'Billingaddress'=>$billingAddress,
			'Shippingaddress'=>$shippingAddress
		);	
	}
}
?>